package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        log.info("login方法调用，方法参数：==>{}",dto);
        //校验参数
        if(dto.getEquipmentId()==null &&(StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPhone()))){
                   return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"手机号或者设备id不存在");
        }
        Map map=new HashMap<>();
        //手机号+密码登录
         if(StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
             //使用手机号+密码 登录
             //根据手机号 查询用户
             ApUser apUser = apUserMapper.selectOne(
                     Wrappers.<ApUser>lambdaQuery()
                             .eq(ApUser::getPhone, dto.getPhone())
             );
             if(apUser==null){
                 return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
             }
             //根据输入的密码+salt 进行md5加密
             String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
             //和数据库中密码对比 如果一致生成token
             if (pwd.equals(apUser.getPassword())){
                 apUser.setPassword("");
                 apUser.setSalt("");
                 map.put("user",apUser);
                 String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                 map.put("token",token);
                 return ResponseResult.okResult(map);
             }else {
                 return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
             }
         }else {
             //使用设备登录
             String token = AppJwtUtil.getToken(0L);
             map.put("token",token);
             return ResponseResult.okResult(map);
         }
    }
}
